package interviewpreparationkit.dictionary

/**
 * [Sherlock and Anagrams](https://www.hackerrank.com/challenges/sherlock-and-anagrams)
 */
// Complete the sherlockAndAnagrams function below.
fun sherlockAndAnagrams(s: String): Int {
    /**
     * 获取指定长度的所有子字符串
     */
    fun getAllSubString(str: String, len: Int): List<String> {
        return (0..str.length - len).map { str.substring(it, it + len) }
    }

    // 字符串长度为1的情况
    var totalCount = getAllSubString(s, 1)
        .groupBy { it }
        .map { it.value.size }
        .filter { it > 1 }
        .map { it * (it - 1) / 2 }
        .sum()

    val maxLength = s.length - 1
    for (i in 2..maxLength) {
        totalCount += getAllSubString(s, i)
            .groupBy { it.toCharArray().sorted().joinToString() }
            .map { it.value.size }
            .filter { it > 1 }
            .map { it * (it - 1) / 2 }
            .sum()
    }

    return totalCount
}